package com.ruoyi.framework.interceptor;

import com.ruoyi.appuser.domain.Appuser;
import com.ruoyi.appuser.service.IAppuserService;
import com.ruoyi.common.annotation.PassToken;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.exception.NoLoginException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Objects;


@Component
public class AppApiInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisCache redisCache;

    @Resource
    private IAppuserService appuserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从 http 请求头中取出 token
        String token = request.getHeader("token");
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();


        //检查方法是否有passtoken注解，有则跳过认证，直接通过
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        // 执行认证
        if (token == null) {
            throw new NoLoginException("无token，请重新登录");
        }
        // 从redis中获取信息
        Appuser appUserCache = redisCache.getCacheObject(token);
        if (Objects.isNull(appUserCache) || null == appUserCache.getId()){
            throw new NoLoginException("token过期,请重新登录");
        }else{
            Appuser appuser = appuserService.getById(appUserCache.getId());
            if (Objects.isNull(appuser) || null == appuser.getId()){
                throw new NoLoginException("token验证失败,该用户不存在");
            }
        }
        return true;
    }

    /**
     * 目标方法执行后
     * 该方法在控制器处理请求方法调用之后、解析视图之前执行
     * 可以通过此方法对请求域中的模型和视图做进一步修改
     */
    @Override
    public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView
            modelAndView) throws Exception {
        System.out.println("postHandle执行{}");

    }
    /**
     * 页面渲染后
     * 该方法在视图渲染结束后执行
     * 可以通过此方法实现资源清理、记录日志信息等工作
     */
    @Override
    public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception
            ex) throws Exception {
        System.out.println("afterCompletion执行异常");

    }

}
